import { service } from '@/config/axios'

import { AxiosPromise } from 'axios'

import { config } from '@/config/axios/config'

const { default_headers } = config

const request = <T>(option: AxiosConfig): AxiosPromise<T> => {
  const { url, method, params, data, headersType, responseType } = option

  return service({
    url: url,
    method,
    params,
    data,
    responseType: responseType,
    headers: {
      'Content-Type': headersType || default_headers
    }
  })
}

function getFn<T = any>(option: AxiosConfig): AxiosPromise<T> {
  return request<T>({ method: 'get', ...option })
}

function getXww<T = any>(option: AxiosConfig): AxiosPromise<T> {
  return request<T>({ method: 'get', headersType: 'application/x-www-form-urlencoded', ...option })
}
function postFn<T = any>(option: AxiosConfig): AxiosPromise<T> {
  return request<T>({ method: 'post', ...option })
}
function postXww<T = any>(option: AxiosConfig): AxiosPromise<T> {
  return request<T>({ method: 'post', headersType: 'application/x-www-form-urlencoded', ...option })
}
/***
 * @description 上传一个文件或多个文件时不能写'multipart/form-data'，不然Linux下不生成boundary=信息
 * @author Elwin ZHANG
 * @date 2022/8/16 9:40
 */
function upload<T = any>(option: AxiosConfig): AxiosPromise<T> {
  return requestMultiPart<T>({ method: 'post', ...option })
}
/***
 * @description upload多文件上传不需要默认content_type
 * @author Elwin ZHANG
 * @date 2023/3/9 15:40
 */
const requestMultiPart = <T>(option: AxiosConfig): AxiosPromise<T> => {
  const { url, method, params, data, responseType } = option
  return service({
    url: url,
    method,
    params,
    data,
    responseType: responseType
  })
}

function deleteFn<T = any>(option: AxiosConfig): AxiosPromise<T> {
  return request<T>({ method: 'delete', ...option })
}

function putFn<T = any>(option: AxiosConfig): AxiosPromise<T> {
  return request<T>({ method: 'put', ...option })
}

export const useAxios = () => {
  return {
    get: getFn,
    post: postFn,
    delete: deleteFn,
    put: putFn,
    postXww: postXww,
    getXww: getXww,
    upload: upload
  }
}
